package com.controller;

import com.dao.IStudentsDAO;
import com.vo.Students;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class LoginController {
    @Autowired
    private IStudentsDAO studentsDAO;

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam String studentId,
                        @RequestParam String studentPwd,
                        HttpSession session,  // 正确用法
                        Model model) {
        Students student = studentsDAO.validateStudent(studentId, studentPwd);
        if (student != null) {
            session.setAttribute("currentUser", student);
            return "redirect:/messages";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
}